/* eslint-disable */
/**
 * * CDN 加载
 * * 自动更换CDN源
 */

const originCdn = 'https://cdn.bootcss.com'

const backupCdns = [
  'https://www.skyworthedu.com.cn/cdn',
  'https://www.skyworthedu.com.cn',
] // 可配置多个

// 监听资源加载错误
window.addEventListener(
  'error',
  event => {
    const flag = event.target.dataset

    if (flag && flag.type && flag.type.toLowerCase() === 'cdn') {
      const src = event.target.src

      const [origin, target] = getOriginAndTarget(src)

      if (!origin || !target) return

      // 插入新节点
      createScript(src.replace(origin, target))
    }
  },
  true
)
// 添加main.js和main.css
window.addEventListener('load', () => {
  cssArr.forEach(element => createLink(element))
  jsArr.forEach(element => createScript(element))
})

// 创建新的script标签
function createScript(src) {
  const script = document.createElement('script')
  script.type = 'text/javascript'
  script.src = src
  script.dataset.type = 'cdn'
  append(document.body, script)
}

// 创建新的link标签
function createLink(href) {
  const link = document.createElement('link')
  link.rel = 'stylesheet'
  link.href = href
  append(document.head, link)
}

// 获取当前cdn源和将要替换的cdn源
function getOriginAndTarget(src) {
  const index = backupCdns.findIndex(cdn => src.indexOf(cdn) >= 0)
  if (index < 0) return [originCdn, backupCdns[0]]
  else if (index < backupCdns.length - 1)
    return [backupCdns[index], backupCdns[index + 1]]
  else return [backupCdns[index], false]
}

// 添加节点操作
function append(dom, node) {
  if (dom.append) dom.append(node)
  else dom.appendChild(node)
}
